package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.service.MemberService;
import constant.CookieMessageConstant;
import constant.MessageConstant;
import entity.Result;
import org.springframework.web.bind.annotation.*;
import pojo.Member;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    
    @Reference
    private MemberService memberService;
    
    /**
     * 校验用户输入的短信验证码是否正确，如果验证码错误则登录失败
     * 如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
     * 向客户端写入Cookie，内容为用户手机号
     * 将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
     */
    @RequestMapping("/login")
    public Result login(HttpServletResponse response,@RequestBody Map map, @RequestParam("myCode") String myCode){
        String phoneNumber = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");//输入的验证码
        String trueCode = myCode;//真正的验证码
        
        if(trueCode == null || !trueCode.equals(validateCode)){
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);//验证码错误
        }
        Member member = null;
        try{
            member = memberService.findMemberByPhoneNumber(phoneNumber);
            if(member == null){
                //不是会员，进行注册
                member = new Member();
                member.setPhoneNumber(phoneNumber);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //会员已存在
            
            //电话写入Cookie,跟踪用户
            Cookie cookie = new Cookie(CookieMessageConstant.Cookie_LOGIN_MEMBER_PHONENUMBER,phoneNumber);
            //设置路径，多个项目间共享cookie
            cookie.setPath("/");
            //设置有效期,30天
            cookie.setMaxAge(60*60*24*30);
            //发送Cookie
            response.addCookie(cookie);
            
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.LOGIN_FAIL);
    }
}
